/*
 * Copyright (c) 2011 Ball State University
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * NOTE:
 * Derivative work based on the Google IO 2011 Schedule app released for open source
 * http://code.google.com/p/iosched/
 */

package edu.bsu.android.gtv.apps.bconnected.ui;

import java.util.ArrayList;

import edu.bsu.android.gtv.apps.bconnected.data.ConnectionData;
import edu.bsu.android.gtv.apps.bconnected.R;
import edu.bsu.android.gtv.apps.bconnected.data.OrganizationData;
import edu.bsu.android.gtv.apps.bconnected.data.PersonData;
import edu.bsu.android.gtv.apps.bconnected.objects.Organization;
import edu.bsu.android.gtv.apps.bconnected.objects.Person;
import edu.bsu.android.gtv.apps.bconnected.ui.HomeActivity;
import edu.bsu.android.gtv.apps.bconnected.ui.base.BaseActivity;
import edu.bsu.android.gtv.apps.bconnected.util.Adapters;
import edu.bsu.android.gtv.apps.bconnected.util.AnalyticsUtils;
import edu.bsu.android.gtv.apps.bconnected.util.Constants;
import edu.bsu.android.gtv.apps.bconnected.util.FractionalTouchDelegate;
import edu.bsu.android.gtv.apps.bconnected.util.LoginHelper;
import edu.bsu.android.gtv.apps.bconnected.util.UIUtils;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.RectF;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.CompoundButton;
import android.widget.ListView;
import android.widget.LinearLayout;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.CompoundButton.OnCheckedChangeListener;

/**
 * An activity that shows detail information for a member, including shared organizations. Activity that is started when a user selects a 
 * member from the list on the {@link OrganizationInfoActivity}.
 * @author Kyle Parker, University Computing Services
 */
public class MemberInfoActivity extends BaseActivity {
    private static final String TAG = "MemberInfoActivity";
    private static final String TAG_SHARED_ORGANIZATIONS = "shared"; 

    private TabHost mTabHost;
    private View mLoadingSpinner;
    private View mSharedOrganizationsSpinner;
    private Activity mActivity;
    private BroadcastReceiver mReceiver;
    private CompoundButton mStarred;
    private Person mPerson;

    private String mBSUID;
    private String mLoginGuid;
    private String mMemberBSUID;
    private boolean mLogin;
    
    private String mMemberRole = "";
    private String mMemberTypeID = "";
    private int mOrganizationPosition = 0;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_member_info);
		
        getActivityHelper().setupActionBar(false, "Student Orgs | Member Info");        
        mActivity = this;
        
        handleLogout();    
        handleLogin();
                
        mTabHost = (TabHost) findViewById(android.R.id.tabhost);
       	mTabHost.setup();

        mLoadingSpinner = findViewById(R.id.loading_spinner); 
        mLoadingSpinner.setVisibility(View.VISIBLE);	
        
        mSharedOrganizationsSpinner = findViewById(R.id.spinner_shared_organizations); 
        mSharedOrganizationsSpinner.setVisibility(View.VISIBLE);
        
        mStarred = (CompoundButton) findViewById(R.id.star_button);
        mStarred.setFocusable(true);
        mStarred.setClickable(true);
        
        // Larger target triggers star toggle
        final View starParent = findViewById(R.id.name);
        FractionalTouchDelegate.setupDelegate(starParent, mStarred, new RectF(0.6f, 0f, 1f, 0.8f));

        setupSharedOrganizationsTab();
        getExtras();

		// Hide the member while the data is loading
        hideMemberInfo();
		if (mLogin) {
			loadMemberInfo();
		}

        AnalyticsUtils.getInstance(mActivity).trackPageView("/MemberInfo");
    }
    
    @Override 
    public void onDestroy() {
    	super.onResume();
    	mActivity.unregisterReceiver(mReceiver);
    }
    
    /**
     * Get the extras from the Intent
     */
    public void getExtras() {
		Bundle extras = getIntent().getExtras(); 

		if (extras != null) {
			if (extras.getString(Constants.EXTRA_BSU_ID) != null) {
				mMemberBSUID = extras.getString(Constants.EXTRA_BSU_ID);
			}
			if (extras.getString(Constants.EXTRA_PERSON_TYPE_ID) != null) {
				mMemberTypeID = extras.getString(Constants.EXTRA_PERSON_TYPE_ID);
			}
			if (extras.getString(Constants.EXTRA_MEMBER_ROLE) != null) {
				mMemberRole = extras.getString(Constants.EXTRA_MEMBER_ROLE);
			}
			if (extras.getString(Constants.EXTRA_ORGANIZATION_POSITION) != null) {
				mOrganizationPosition = Integer.parseInt(extras.getString(Constants.EXTRA_ORGANIZATION_POSITION));
			}
		}
    }

    /**
     * Using a new thread, separate from the main activity, load the member information from the service handler
     */
    private void loadMemberInfo() {		
        Runnable load = new Runnable(){
            public void run() { 
            	try {
	            	// Depending on the member type (student or advisor) retrieve the appropriate person information
	            	if (Integer.parseInt(mMemberTypeID) == Constants.VALUE_PERSON_TYPE_FACULTY) {
	            		PersonData.initializePerson(mMemberBSUID, mBSUID, Constants.QUERY_PERSON_DIRECTORY_FACULTY, mActivity);
	            	} else {
	            		PersonData.initializePerson(mMemberBSUID, mBSUID, Constants.QUERY_PERSON_DIRECTORY_STUDENT, mActivity);
	            	}
	            	
	                if (PersonData.getPersonCount() > 0) {
	                	// This will return 1 person record - retrieve the information from the first position
	                	mPerson = PersonData.getPerson(0);
                    }
	    	    	
	        		mActivity.runOnUiThread(returnMember);
            	} catch (Exception ex) {
                    AnalyticsUtils.getInstance(mActivity).trackPageView(TAG + ": " + ex.getMessage());
            	}
            }
        };
        
        Thread thread = new Thread(null, load, "loadMember");
        thread.start();
    }
    /**
     * Load the member info from the service handler and set the visibility of the spinner to "gone"
     */
    private Runnable returnMember = new Runnable(){
        public void run() {
        	displayMember();
            mLoadingSpinner.setVisibility(View.GONE);
        }
    };

    /**
     * Using a new thread, separate from the main activity, load the shared organizations from the service handler
     */
    private void loadSharedOrganization() {			
        Runnable load = new Runnable(){
            public void run() { 
            	try {
            		OrganizationData.initializeSharedOrganization(mBSUID, mPerson.getBSUID(), mActivity);
        	    	
            		mActivity.runOnUiThread(returnSharedOrganization);
            	} catch (Exception ex) {
                    AnalyticsUtils.getInstance(mActivity).trackPageView(TAG + ": " + ex.getMessage());
            	}
            }
        };
        
        Thread thread = new Thread(null, load, "loadSharedOrganization");
        thread.start();
    }
    
    /**
     * Display the shared organizations in a separate thread
     */
    private Runnable returnSharedOrganization = new Runnable(){
        public void run() {                        
            displaySharedOrganizations(OrganizationData.getSharedOrganizations());
            mSharedOrganizationsSpinner.setVisibility(View.GONE);
            
            if (OrganizationData.getSharedOrganizationCount() == 0) {
                TextView empty = ((TextView) findViewById(R.id.empty_shared_organizations));
                empty.setVisibility(View.VISIBLE);
            }
        }
    };
    
    /**
     * Display the member information, set the starred status and show the shared organizations
     */
    private void displayMember() { 
    	if (mPerson != null) {
    		LinearLayout view = (LinearLayout) findViewById(R.id.member_info_container);
            view.setVisibility(View.VISIBLE);
        	view.setBackgroundResource(R.color.content_background);
            
            loadSharedOrganization();
            
            String name;
            
        	if (Integer.parseInt(mMemberTypeID) == Constants.VALUE_PERSON_TYPE_FACULTY) {	            
        		name = (mPerson.getNamePrefix() + " " + mPerson.getFirstName() + " " + mPerson.getLastName() + " " + mPerson.getNameSuffix()).trim();

        		view.findViewById(R.id.address).setVisibility(View.GONE);
	    		view.findViewById(R.id.department).setVisibility(View.VISIBLE);
	    		view.findViewById(R.id.office).setVisibility(View.VISIBLE);
	            
	            UIUtils.displayTextView(view, R.id.department, mPerson.getDepartment());
	            UIUtils.displayTextView(view, R.id.office, mPerson.getBuildingCode() + " " + mPerson.getRoom());
        	} else {
        		name = (mPerson.getFirstName() + " " + mPerson.getLastName() + " " + mPerson.getNameSuffix()).trim();
        		
        		view.findViewById(R.id.department).setVisibility(View.GONE);
        		view.findViewById(R.id.office).setVisibility(View.GONE);
	        	view.findViewById(R.id.address).setVisibility(View.GONE);
        	}
	        
            // Unregister around setting checked state to avoid triggering
            // listener since change isn't user generated.
            mStarred.setOnCheckedChangeListener(null);
            mStarred.setChecked(mPerson.getStarred());
            mStarred.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
			    	ConnectionData.insertConnection(mBSUID, mLoginGuid, mMemberBSUID, Integer.parseInt(mMemberTypeID), isChecked, mActivity);
			    }           	
            });
            
    		UIUtils.displayTextView(view, R.id.name, name);
    		UIUtils.displayTextView(view, R.id.title, mMemberRole);
    		UIUtils.displayTextView(view, R.id.email, mPerson.getEmailAddress());
    		UIUtils.displayTextView(view, R.id.phone, mPerson.getPhone());	        
        } else {
        	hideMemberInfo();
    		((TextView) showEmptyMemberInfo().findViewById(R.id.empty_member_info)).setText(R.string.empty_member_info);
    	}
    }

    /**
     * Hide the member view during the load process or if the member object is empty
     */
	private void hideMemberInfo() {  
		LinearLayout view = (LinearLayout) findViewById(R.id.member_info_container);
        view.setVisibility(View.GONE);			
	}

    /**
     * Show the member view during the load process or if the member object is empty
     */
	private View showEmptyMemberInfo() {
		LinearLayout view = (LinearLayout) findViewById(R.id.empty_member_info_container);
		view.setVisibility(View.VISIBLE);
        view.setBackgroundResource(R.drawable.empty_student_orgs);
        
        return view;
	}
    
    /**
     * Display the shared organizations for the student and the member
     */
    private void displaySharedOrganizations(ArrayList<Organization> sharedOrganizations) {
    	Adapters.OrganizationAdapter adapter = new Adapters.OrganizationAdapter(mActivity, sharedOrganizations, 
    			Constants.TARGET_SHARED_ORGANIZATION);

        final ListView lv = ((ListView) findViewById(R.id.shared_organizations));
        lv.setAdapter(adapter);  
        lv.setOnItemClickListener(new OnItemClickListener(){
			public void onItemClick(AdapterView<?> parentView, View childView, int position, long id) {
		        final Intent intent = new Intent(Intent.ACTION_VIEW, null, mActivity, OrganizationInfoActivity.class);

		        // In order to get the correct organization on the organization info activity, get the ID at the position specified 
		        // and return as an extra in the intent
		        Organization org = (Organization) lv.getItemAtPosition(position);
				
		        intent.putExtra(Constants.EXTRA_MEMBER_POSITION, Integer.toString(position));
		        intent.putExtra(Constants.EXTRA_ORGANIZATION_ID, org.getOrganizationID());
		        intent.putExtra(Constants.EXTRA_ORGANIZATION_POSITION, Integer.toString(mOrganizationPosition));

		        mActivity.startActivity(intent);
			}
		});
    }
    
    /**
     * Build and add "shared organizations" tab.
     */
    private void setupSharedOrganizationsTab() {
        mTabHost.addTab(mTabHost.newTabSpec(TAG_SHARED_ORGANIZATIONS) 
                .setIndicator(UIUtils.buildIndicator(R.string.tab_member_shared_organizations, mActivity))
                .setContent(R.id.tab_shared_organization));
    }

    /**
     * In order to protect the activity from the back stack after a student logs out, remove the activity 
     * If the student hits the back button, this will take them to the Home activity
     */
    private void handleLogout() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Constants.ACTION_LOGOUT);
        mReceiver = new BroadcastReceiver() {
			@Override
			public void onReceive(Context context, Intent intent) {
		        intent = new Intent(Intent.ACTION_VIEW, null, mActivity, HomeActivity.class);
		        intent.putExtra(Constants.EXTRA_LOGIN_STATUS, Integer.toString(Constants.LOGIN_STATUS_LOGOUT));
		        
		        mActivity.startActivity(intent); 
			    mActivity.finish();
			}
		};
		
        mActivity.registerReceiver(mReceiver, intentFilter);
    }
    
    /**
     * Determine if the person has logged in and whether there is a person object in the database
     * Get the student's BSU ID for use throughout the application
     */
    private void handleLogin() {
    	Person person = LoginHelper.checkLogin(mActivity);
    	
    	if (person != null) {
    		mBSUID = person.getBSUID();     
    		mLoginGuid = person.getLoginGuid();
        	mLogin = true;
    	} else {
	        Intent intent = new Intent(Intent.ACTION_VIEW, null, mActivity, HomeActivity.class);
	        intent.putExtra(Constants.EXTRA_LOGIN_STATUS, Integer.toString(Constants.LOGIN_STATUS_NOT_LOGGED_IN));
	        
	        mActivity.startActivity(intent); 
		    mActivity.finish();
		    
		    mLogin = false;
    	}    	
    }
}
